/**
 * Project oo_thread
 */


#include "../include/MySQLConnector.h"
#include "../include/LoginGetcrypt.h"
#include <ctime>
#include <stdlib.h>
#include <iostream>
#include <unistd.h>
using std::endl;
using std::cout;
enum TaskType{
    TASK_LOGIN_SECTION1 = 1, 
    TASK_LOGIN_SECTION1_RESP_OK,
    TASK_LOGIN_SECTION1_RESP_ERROR,
    TASK_LOGIN_SECTION2,
    TASK_LOGIN_SECTION2_RESP_OK,
    TASK_LOGIN_SECTION2_RESP_ERROR,
    TASK_TYPE_REGISTER1,
    TASK_TYPE_REGISTER1_RESP_OK,
    TASK_TYPE_REGISTER1_RESP_ERROR,
    TASK_TYPE_GEGISTER2,
    TASK_TYPE_REGISTER2_RESP_OK
};   

/**
 * RegisterTask implementation
 */
LoginGetcrypt::LoginGetcrypt(const string msg, TcpConnectionPtr conn)
    :_msg(msg)
     ,_conn(conn)
{

}
bool LoginGetcrypt::isMatch(const string & msg)
{
    if(!_msg.size())
    {
        LOG_WARN("msg is empty");
        return false;
    }
    //解析字符
    MySQLConnector* mysqlconn = MySQLConnector::getInstance();
    string crypt;
    string username;
    if(parseString(msg, crypt, username) && mysqlconn->compareCrypt(username, crypt))
    {
        return true;   
    }
    else
    {
        LOG_INFO("fail parseString");
        return false;
    }
}

bool LoginGetcrypt::parseString(const string & msg, string & crypt, string & username)
{
    size_t pos = msg.find("=");
    if(pos == std::string::npos)
    {
        LOG_INFO("cant find '='");
        return false;
    }
    username = msg.substr(0,pos);
    crypt = msg.substr(pos + 1);
    return true;
}
/**
 * @return void
 */
void LoginGetcrypt::process() {

    //handle msg
    cout << "LoginGetcrypt handle msg" << endl;
    sleep(1);
    cout << "crypt = " << _msg << endl; 
    //查询数据库并比对密文
    if(isMatch(_msg))
    {
        _conn->sendtoLoop(TASK_LOGIN_SECTION2_RESP_OK
                          ,"login success");
    }
    else
    {
        _conn->sendtoLoop(TASK_LOGIN_SECTION2_RESP_ERROR
                          ,"login false");
    }
}
